﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using WebBrowser = System.Windows.Forms.WebBrowser;
using Newtonsoft.Json.Linq;
namespace DataCollectionSystem
{
	/// <summary>
	/// DataWindow.xaml 的交互逻辑
	/// </summary>
	[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
	[System.Runtime.InteropServices.ComVisibleAttribute(true)]
	public partial class DataWindow : Window
	{
		string Device_id;
		Dictionary<WebBrowser, Dictionary<string, string>> SensorTypes_diagnostics = new Dictionary<WebBrowser, Dictionary<string, string>>();
		System.Timers.Timer t;
		public DataWindow(string device_id)
		{
			InitializeComponent();
			Device_id = device_id;

			try
			{
				List<Dictionary<string, string>> SensorTypes = ApiService.GetSensorType(device_id);

				for (int i = 0; i < SensorTypes.ToArray().Length; i++)
				{
					TabItem tabItem = new TabItem();

					tabItem.Header = SensorTypes[i]["Name"];



					WindowsFormsHost windowsFormsHost = new WindowsFormsHost();
					WebBrowser webBrowser = new WebBrowser();
					windowsFormsHost.Child = webBrowser;

					SensorTypes_diagnostics.Add(webBrowser, SensorTypes[i]);
					//加载网页
					webBrowser.Navigate(Environment.CurrentDirectory + @"\ECharts.html");
					webBrowser.ScriptErrorsSuppressed = true; //禁用错误脚本提示 
					webBrowser.IsWebBrowserContextMenuEnabled = false; //禁用右键菜单                         
					webBrowser.AllowWebBrowserDrop = false;//禁止拖拽
					webBrowser.ScrollBarsEnabled = false;//禁止滚动条
					webBrowser.WebBrowserShortcutsEnabled = false; //禁用快捷键

					webBrowser.DocumentCompleted += documentComplete;

					tabItem.Content = windowsFormsHost;
					type_data.Items.Add(tabItem);


				}



			}

			catch (Exception ex)
			{
				System.Windows.MessageBox.Show(ex.Message, "错误");
			}

			t = new System.Timers.Timer(5000);//定时器 1s执行一次theout
			t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件；
			t.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
			t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
		}
		public void theout(object source, System.Timers.ElapsedEventArgs e)
		{
			foreach (var item in SensorTypes_diagnostics)
			{
				WebBrowser webBrowser = item.Key;
				//刷新页面
				this.Dispatcher.Invoke(() =>
				{
					updateData(webBrowser);
				});
			}

		}
		public void setData(WebBrowser webBrowser)
		{
			object[] obj;
			object ret = null;
			obj = new object[3];



			obj[0] = SensorTypes_diagnostics[webBrowser]["Name"];
			obj[1] = SensorTypes_diagnostics[webBrowser]["unit"];
			if ((string)obj[1] == "%")
				obj[2] = 100;
			ret = RunMethod(webBrowser, "showTable", obj);
		}
		public void updateData(WebBrowser webBrowser)
		{
			object ret = null;
			List<Dictionary<string, string>> SensorData = null;
			try
			{
				SensorData = ApiService.GetSensorData(Device_id, SensorTypes_diagnostics[webBrowser]["type_name"]);
			}
			catch (Exception ex)
			{
				System.Windows.MessageBox.Show(ex.Message, "错误");
			}
			if (SensorData != null)
			{
				object[] arg;
				arg = new object[1];

				JArray Data = new JArray();

				for (int i = 0; i < SensorData.ToArray().Length; i++)
				{
					JObject jObject = new JObject();
					JArray jArray = new JArray();
					jArray.Add(SensorData[i]["date"]);
					jArray.Add(SensorData[i]["data"]);
					jObject.Add("name", SensorData[i]["date"]);
					jObject.Add("value", jArray);
					Data.Add(jObject);

				}
				arg[0] = Data.ToString();

				//更新数据
				ret = RunMethod(webBrowser, "addDataArray", arg);
				object[] arg2;
				arg2 = new object[2];
				arg2[0] = SensorData[0]["date"];
				arg2[1] = SensorData[0]["data"];
				ret = RunMethod(webBrowser, "setData", arg2);

				System.GC.Collect();



			}
			else
				System.Windows.MessageBox.Show(SensorTypes_diagnostics[webBrowser]["Name"] + "没有数据");
		}
		public void documentComplete(object sender, WebBrowserDocumentCompletedEventArgs e)
		{




			WebBrowser webBrowser = (WebBrowser)sender;

			if (!webBrowser.IsBusy)
			{
				setData(webBrowser);
				updateData(webBrowser);

			}
		}
		/// <summary>
		/// 调用JS函数
		/// </summary>
		/// <param name="webrowser">网页窗体</param>
		/// <param name="scriptName">函数名</param>
		/// <param name="args">参数</param>
		/// <returns></returns>
		public object RunMethod(System.Windows.Forms.WebBrowser webrowser, String scriptName, object[] args)
		{
			return webrowser.Document.InvokeScript(scriptName, args);
		}

		private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			t.Stop();
		}
	}
}


